<?php

declare(strict_types=1);


namespace app\controller\mini;

use app\controller\admin\AdminBaseController;
use app\Request;
use app\model\admin\SysMember;
use app\model\mini\MiniUser;
use app\model\mini\Poster;
use Kkokk\Poster\PosterManager;
use Exception;
use Kkokk\Poster\Exception\Exception as PostException;
use Kkokk\Poster\Facades\Poster as KPoster;

class PosterController extends AdminBaseController
{
    // public function getCode(Request $request)
    // {
    //     // 运营商id
    //     $user_id = $request->create_by;
    //     $info = SysMember::find($user_id);
    //     if ($info->poster) {
    //         return success($info->poster);
    //     } else {
    //         $res = $this->miniApp->app_code->getUnlimit("from_op&" . $user_id);
    //         if ($res instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
    //             $filename = $res->saveAs(public_path('storage/poster'), md5(time() . '') . '.png');
    //             // 保存至表
    //             $info->poster = "storage/poster/" . $filename;
    //             $info->save();
    //             return success("storage/poster/" . $filename);
    //         } else {
    //             return error('生成失败,请稍后重试');
    //         }
    //     }
    // }

    public function getPosterList(Request $request)
    {
        $user_id = $request->user_id;
        $list = Poster::where([
            "type" => 1,
            "status" => 1
        ])->select()->toArray();
        $user = MiniUser::find($user_id);
        $qrCode = "";
        if ($user->code_url) {
            $qrCode = $user->code_url;
        } else {
            // 生成二维码
            $res = $this->miniApp->app_code->getUnlimit("from_parent&" . $user_id, [
                "page" => "pages/index/index",
                "env_version" => $this->miniInfo['env_version']
            ]);
            if ($res instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $filename = $res->saveAs(public_path('storage/poster'), md5(time() . '') . '.png');
                // 保存至表
                $user->code_url = "storage/poster/" . $filename;
                $user->save();
                $qrCode = "storage/poster/" . $filename;
                // return success("storage/poster/" . $filename);
            } else {
                return error('生成失败,请稍后重试');
            }
        }
        foreach ($list as $key => &$val) {
            // 生成海报
            $generateRes = $this->generatePoster($val, $user, $qrCode);
            if ($generateRes['res']) {
                $val['url'] = $generateRes['path'];
            } else {
                continue;
            }
        }
        return success($list);
    }
    public function generatePoster($posterInfo, $mp_user_info, $wx_code_url)
    {
        storage_log("创建海报");
        $nickname_info = null;
        $time_info = null;
        $date_info = null;
        $avatar_info = null;
        $expire_time_info = null;
        if ($posterInfo['avatar_info']) {
            $avatar_info = json_decode($posterInfo['avatar_info']);
        }
        if ($posterInfo['nickname_info']) {
            $nickname_info = json_decode($posterInfo['nickname_info']);
            storage_log('nickname_info' . $posterInfo['nickname_info']);
            $nicknameColor = hex2rgba($nickname_info->font_color, false, true);
        }
        if ($posterInfo['date_info']) {
            $date_info = json_decode($posterInfo['date_info']);
            $dateColor = hex2rgba($date_info->font_color, false, true);
        }
        if ($posterInfo['time_info']) {
            $time_info = json_decode($posterInfo['time_info']);
            $timeColor = hex2rgba($time_info->font_color, false, true);
        }
        // storage_log("expire_time_info" . $posterInfo['expire_time_info']);
        // if ($posterInfo['expire_time_info']) {
        //     $expire_time_info = json_decode($posterInfo['expire_time_info']);
        //     $expireTimeColor = hex2rgba($expire_time_info->font_color, false, true);
        // }
        //二维码必须要有
        $qrcode_info = json_decode($posterInfo['qrcode_info']);
        $date = date('Y-m-d');
        $time = date('H:i:s');
        $dataName = date("Ymd") . '/poster' . date("YmdHis") . rand(100, 999) . rand(100, 999) . rand(100, 999);

        try {
            $path = app()->getRootPath() . 'public/storage/uploads/' . $dataName . ".png";
            $bgImg = app()->getRootPath() . 'public/' . $posterInfo['bg_img'];
            $backgroundInfo = getimagesize($bgImg);
            $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
            $background = $backgroundFun($bgImg);
            $backgroundWidth = imagesx($background);    //背景宽度
            $backgroundHeight = imagesy($background);

            $wRate = round($backgroundWidth / $posterInfo['bg_img_width'], 2);
            $hRate = round($backgroundHeight / $posterInfo['bg_img_height'], 2);

            storage_log("path" . $path);
            // $basePoster = new PosterManager($path);
            $basePoster = PosterManager::Poster();
            $basePoster = KPoster::config([
                'path' => $path
            ]);
            // var_dump($basePoster);
            // $basePoster->path($path);

            $basePoster->buildImDst($posterInfo['bg_img']);

            if ($mp_user_info->avatar && $avatar_info) {
                // $basePoster->buildImage($mp_user_info->avatar, $avatar_info->left * $wRate, $avatar_info->top * $hRate, 0, 0, $avatar_info->width * $wRate, $avatar_info->height * $hRate);
                $basePoster->buildImage(app()->getRootPath() . 'public/' . $mp_user_info->avatar_url, $avatar_info->left, $avatar_info->top, 0, 0, $avatar_info->width, $avatar_info->height);
            }
            if ($mp_user_info->nickname && $nickname_info) {
                $basePoster->buildText($mp_user_info->nickname, $nickname_info->left * $wRate, $nickname_info->top * $hRate, $nickname_info->font_size * $wRate, [$nicknameColor[0], $nicknameColor[1], $nicknameColor[2], 1]);

                // $basePoster->buildText($mp_user_info->nickname, $nickname_info->left, $nickname_info->top, $nickname_info->font_size, [$nicknameColor[0], $nicknameColor[1], $nicknameColor[2], 1]);
            }
            if ($time_info) {
                $basePoster->buildText($time, $time_info->left * $wRate, $time_info->top * $hRate, $time_info->font_size * $wRate, [$timeColor[0], $timeColor[1], $timeColor[2], 1]);

                // $basePoster->buildText($time, $time_info->left, $time_info->top, $time_info->font_size, [$timeColor[0], $timeColor[1], $timeColor[2], 1]);
            }
            if ($date_info) {
                $basePoster->buildText($date, $date_info->left * $wRate, $date_info->top * $hRate, $date_info->font_size * $wRate,  [$dateColor[0], $dateColor[1], $dateColor[2], 1]);

                // $basePoster->buildText($date, $date_info->left, $date_info->top, $date_info->font_size,  [$dateColor[0], $dateColor[1], $dateColor[2], 1]);
            }
            // var_dump($wx_code_url);
            // $result = $basePoster->buildQr("http://www.520yummy.com", $qrcode_info->left * $wRate, $qrcode_info->top * $hRate, 0, 0, $qrcode_info->width * $wRate, $qrcode_info->height * $hRate)
            //     ->getPoster();
            $result = $basePoster->buildImage(env('APP_URL') . "/" . $wx_code_url, $qrcode_info->left * $wRate, $qrcode_info->top * $hRate, 0, 0, $qrcode_info->width * $wRate, $qrcode_info->height * $hRate)
                ->getPoster();
            // $result = $basePoster->buildQr($wx_code_url, $qrcode_info->left, $qrcode_info->top, 0, 0, $qrcode_info->width, $qrcode_info->height)
            //     ->getPoster();
            storage_log("resulr:" . json_encode($result));
        } catch (PostException $e) {
            storage_log('PostException' . $e->getMessage());
            throw new Exception($e->getMessage());
            return ['msg' => $e->getMessage(), 'res' => false];
        }
        $returnPath = "storage/uploads/" . $dataName . ".png";
        return ['msg' => 'success', 'res' => true, 'path' => $returnPath, 'data' => $result];
    }
}
